// --- Copyright (c) 2006-2008 Stefan Kyntchev ---
// This software is written and copyrighted by Stefan Kyntchev 
// and BeyondPod Team members. All rights are reserved.
// Author contact: support@beyondpod.mobi
// ------------------------------------------------------------------------
// This file is part of BeyondPod RSS Feed Reader and Podcast manager
// (www.codeplex.com/BeyondPod) 
// BeyondPod is free software: you can redistribute it and/or modify 
// it under the terms of the GNU General Public License as published by 
// the Free Software Foundation, either version 3 of the License, or 
// (at your option) any later version. 
//  
// BeyondPod is distributed in the hope that it will be useful, 
// but WITHOUT ANY WARRANTY; without even the implied warranty of 
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
// GNU General Public License for more details. 
//  
// You should have received a copy of the GNU General Public License
// along with BeyondPod. If not, see <http://www.gnu.org/licenses/>
// ------------------------------------------------------------------------
// COPYRIGHT NOTICE: This copyright notice may NOT be removed, obscured or modified 
// without written consent from the author.
// --- End copyright notice --- 


using System;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using svs.Mobile.BeyondMedia.Controls;
using svs.Mobile.BeyondMedia.FeedCore;
using svs.Mobile.BeyondMedia.FeedCore.Helpers;
using svs.Mobile.BeyondMedia.FeedCore.RSS;
using svs.Mobile.BeyondMedia.Objects;
using svs.Mobile.BeyondMedia.Properties;
using svs.Mobile.BeyondMedia.UiCore;

namespace svs.Mobile.BeyondMedia.Forms
{
	public partial class Master : Form
	{
		public bool ForceApplicationExit = false;
		public static Master MasterForm;
		private WinMessageHandler _MessageHandler;
		private CmdArgs _StartArgumetns;
		private NotificationManager m_NotificationMgr = new NotificationManager();

		private TransitionControl _TransitionControl;

		public Master(CmdArgs args)
		{
			InitializeComponent();
			MasterForm = this;
			KeyPreview = true;

			_StartArgumetns = args;

			KeyPress += OnKeyPress;

			Enabled = false;
		}

		private void OnKeyPress(object sender, KeyPressEventArgs e)
		{
			if (e.KeyChar == (Char) Keys.Escape)
			{
				e.Handled = true;
				OnBackButton(sender, e);
			}
		}

		private void OnLoad(object sender, EventArgs e)
		{
			bool showWelcome = false;

			Program.WriteSplashInfo("Loading configuration...");

			//Check if our download path is empty
			if (string.IsNullOrEmpty(Configuration.EnclosureDownloadPath))
			{
				//Set it to the Default Download Path
				Configuration.EnclosureDownloadPath = Configuration.DefaultDownloadPath;
				if (!Directory.Exists(Configuration.EnclosureDownloadPath))
				{
					try
					{
						Directory.CreateDirectory(Configuration.EnclosureDownloadPath);
						showWelcome = true;
					}
					catch
					{
						MessageBoxEx.Show(Resources.InvalidFeedDownloadFolderMsg, Resources.InvalidFeedDownloadFolderTitle,
						                  MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
					}
				}
			}

			Program.WriteSplashInfo("Loading feed store...");

			FeedRepository.RootPath = Configuration.EnclosureDownloadPath;

			Program.WriteSplashInfo(string.Format("Loaded {0} feeds, {1} podcasts", FeedRepository.FeedCount, FeedRepository.TrackCount));

			LoadViews();

			Enabled = true;
			Visible = true;
			Program.CloseSplashScreen();

			if (showWelcome)
			{
				var w = new Welcome();
				w.ShowDialog();
			}

			CheckForAvailableDiskSpace();

			StartAutoUpdate();

			_MessageHandler = new WinMessageHandler();

		}

		private void CheckForAvailableDiskSpace()
		{
			if (!IsStartedForOutoUpdate())
			{
				FlashStorageLocation rssCache = new FlashStorageLocation(Configuration.ApplicationInstallPath);
				if (!rssCache.CheckIfSpaceIsAvailable(200*1024))
				{
					MessageBoxEx.Show(
						string.Format(string.Format(Resources.IssuficientStorageSpaceMsg,
						                            rssCache.AvailableSpaceAsString, rssCache.FriendlyLocationName, "200 K"),
						              Resources.IssuficientStorageSpaceTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation,
						              MessageBoxDefaultButton.Button1));
				}
			}
		}

		private void StartAutoUpdate()
		{
			if (IsStartedForOutoUpdate())
			{
				if (string.IsNullOrEmpty(FeedRepository.RootPath))
					FeedRepository.RootPath = Configuration.EnclosureDownloadPath;

				if (_StartArgumetns.ExitAfterUpdate)
					UpdateAndDownloadManager.UpdateAndDownloadBatchCompleted += CommandManager.CmdExitApplication;

				CommandManager.CmdStartBatchUpdate(_StartArgumetns.CategoryToUpdate);
			}
			else if(Configuration.UpdateOnStartup)
			{
				CommandManager.CmdStartBatchUpdate(CategoryManager.AllFeeds);
			}
		}

		private bool IsStartedForOutoUpdate()
		{
			return _StartArgumetns.CategoryToUpdate != CategoryManager.CategoryNull;
		}

		public void CloseForm()
		{
			if (InvokeRequired)
			{
				Invoke(new CloseFormDelegate(CloseForm));
				return;
			}

			Close();
		}

		private void LoadViews()
		{
			try
			{
				Cursor.Current = Cursors.WaitCursor;

				BuildControls();

				CommandManager.SubscribeForControlEvents();

				// A track was playing when we exited
				Track t = null;

				if (string.IsNullOrEmpty(Configuration.LastPlayedTrackPath))
					t = FeedRepository.GetTrackByPath(Configuration.LastPlayedTrackPath);

				if (t != null)
				{
					CommandManager.PlayTrack(t);
				}
				else
				{
					Feed f = null;

					if (Configuration.LastSelectedFeed != Guid.Empty)
						f = FeedRepository.GetFeedById(Configuration.LastSelectedFeed);

					if (f != null)
					{
						// Tere was a selected Feed
						ConfigureFeedsViewNotificationMessages();
						ViewManager.Feeds.SetRootFeed(f.ParentFeed.FeedPath == FeedRepository.RootFeed.FeedPath ?FeedRepository.RootFeed : f.ParentFeed, f);
						ViewManager.CurrentViewName = Helpers.ViewNames.Feeds;
					}
					else
					{
						CommandManager.InitializeFeeds();
					}
				}

				m_NotificationMgr.StartMonitoring();
			}
			catch (OutOfMemoryException)
			{
				MessageBoxEx.Show(
					"There is not enough memory to run BeyondPod. Please close some of your open applications and try again!",
					"Out of memory", MessageBoxButtons.OK, MessageBoxIcon.Hand, MessageBoxDefaultButton.Button1);
			}
			finally
			{
				Cursor.Current = Cursors.Default;
			}
		}

		private static void ConfigureFeedsViewNotificationMessages()
		{
			var feedsView = (ViewManager.Feeds as KineticFeedsView);

			var showNewVersion = false;
			if (VersionCheckManager.VersionInfoAgeInHours < 7 * 24)  // Show new version notification for a week
			{
				if (VersionCheckManager.VersionInfo.IsNewPublicVersionAvailable)
				{
					feedsView.BackgroundHeaderText = string.Format(Resources.NewVersionAvailableMessage, "public",
					                                               VersionCheckManager.VersionInfo.LastPublicVersion);
					showNewVersion = true;
				}
				else if (VersionCheckManager.VersionInfo.IsNewDevVersionAvailable)
				{
					feedsView.BackgroundHeaderText = string.Format(Resources.NewVersionAvailableMessage, "BETA",
					                                               VersionCheckManager.VersionInfo.LastDevVersion);
					showNewVersion = true;
				}
			}

			if(showNewVersion)
			{
			if (VersionCheckManager.VersionInfoAgeInHours < 48)  //automatically show it up for 48 hours 
					feedsView.AutoShowHeader = true;

				feedsView.Settings.HeaderBackgroundColor = Color.FromArgb(0xd4, 0xe6, 0xfc);
				feedsView.Settings.HeaderTextColor = Color.Navy;
				feedsView.Settings.HeaderLineColor = Color.FromArgb(0xbd, 0xca, 0xd8);
			}
			else
			{
				if (VersionCheckManager.VersionInfo.HasMessage)
					feedsView.BackgroundHeaderText = VersionCheckManager.VersionInfo.Message;
				else
					feedsView.BackgroundHeaderText = Resources.DonationPledgeMessage;

				feedsView.AutoShowHeader = Configuration.NextNotificationTime < DateTime.Now;

				if (feedsView.AutoShowHeader)
					Configuration.NextNotificationTime = DateTime.Now.AddDays(2);  //Show the notification once every 2 days

				feedsView.Settings.HeaderBackgroundColor = Color.FromArgb(0xc8,0xe4,0xb3);
				feedsView.Settings.HeaderTextColor = Color.FromArgb(0x4d,0x7f,0x4a);
				feedsView.Settings.HeaderLineColor = Color.FromArgb(0xa5,0xc9,0x8b);
			}

			feedsView.BackgroundFooterText = string.Format(Resources.DefaultFooterText, Configuration.ProductVersion);
		}

		private void BuildControls()
		{
			ITracksView Tracks = new KineticTracksView();
			IFeedsView Feeds = new KineticFeedsView(true);
			var Player = new MediaPlayerView();
			var FeedContentView = new RSSFeedContentView();
			var Browser = new WebBrowserView();
			var Categories = new KineticCategoryListView();
			_TransitionControl = new TransitionControl();

			Controls.Clear();

			_TransitionControl.Dock = DockStyle.Fill;
			_TransitionControl.Location = new Point(0, 0);
			_TransitionControl.Name = "Transition";
			_TransitionControl.Size = ClientSize;
			_TransitionControl.TabIndex = 0;
			_TransitionControl.Visible = false;

			// 
			// Tracks
			// 
			(Tracks as Control).Dock = DockStyle.Fill;
			(Tracks as Control).Location = new Point(0, 0);
			(Tracks as Control).Name = "Tracks";
			(Tracks as Control).Size = ClientSize;
			(Tracks as Control).TabIndex = 1;
			(Tracks as Control).Visible = false;
			
			// 
			// Feeds
			// 
			(Feeds as Control).Dock = DockStyle.Fill;
			(Feeds as Control).Location = new Point(0, 0);
			(Feeds as Control).Name = "Feeds";
			(Feeds as Control).Size = ClientSize;
			Feeds.Visible = false;
			(Feeds as Control).TabIndex = 0;

			// 
			// Player
			// 
			Player.Dock = DockStyle.Fill;
			Player.Location = new Point(0, 0);
			Player.Name = "Player";
			Player.Size = ClientSize;
			Player.Visible = false;
			Player.TabIndex = 2;

			// 
			// WebBrowser
			// 
			FeedContentView.Dock = DockStyle.Fill;
			FeedContentView.Location = new Point(0, 0);
			FeedContentView.Name = "FeedContent";
			FeedContentView.Size = ClientSize;
			FeedContentView.Visible = false;
			FeedContentView.TabIndex = 3;

			Browser.Dock = DockStyle.Fill;
			Browser.Location = new Point(0, 0);
			Browser.Name = "WebBrowser";
			Browser.Size = ClientSize;
			Browser.Visible = false;
			Browser.TabIndex = 3;

			Categories.Dock = DockStyle.Fill;
			Categories.Location = new Point(0, 0);
			Categories.Name = "Categories";
			Categories.Size = ClientSize;
			Categories.Visible = false;
			Categories.TabIndex = 4;

			Controls.Add(_TransitionControl);
			Controls.Add(Categories);
			Controls.Add(Feeds as Control);
			Controls.Add(Tracks as Control);
			Controls.Add(Player);
			Controls.Add(FeedContentView);
			Controls.Add(Browser);

			Player.BackClick += OnBackButton;
			Tracks.BackClick += OnBackButton;
			Feeds.BackClick += OnBackButton;
			FeedContentView.BackClick += OnBackButton;
			Browser.BackClick += OnBackButton;

			ViewManager.Initialize(Feeds as Control, Tracks as Control, Player, FeedContentView, Browser, Categories);
		}

		private static void OnBackButton(object sender, EventArgs e)
		{
			ShortcutKeyManager.HandleKey(Keys.Escape);
		}

		protected override void OnClosing(CancelEventArgs e)
		{
			//e.Cancel = true; // For the Hopper test

			//If we are on some of the other screens - just switch back to the feeds screen
			if (!ForceApplicationExit && ViewManager.CurrentViewName != Helpers.ViewNames.Feeds)
			{
				CommandManager.CmdGoToView(Helpers.ViewNames.Feeds);
				e.Cancel = true;
				return;
			}

			ViewManager.SetCustomTitle("Saving feed store...", false);
			_MessageHandler.Dispose();

			m_NotificationMgr.StopMonitoring();

			if (!FeedRepository.IsEmpty)
				CommandManager.OnBeforeApplicationExit();

			//EQATEC.Profiler.Runtime.TakeProfileSnapshot(@"\Storage Card\BeyondPodProfile.xml");

			base.OnClosing(e);
		}

		protected override void OnPaintBackground(PaintEventArgs e)
		{
		}

		protected override void OnResize(EventArgs e)
		{
			base.OnResize(e);

			if(_TransitionControl != null)
				_TransitionControl.Size = ClientSize;
		}

		public TransitionControl TransitionControl
		{
			get { return _TransitionControl; }
		}

		#region Nested type: CloseFormDelegate

		private delegate void CloseFormDelegate();

		#endregion
	}
}